package com.example.leader;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(LeaderElection.class)
@EnableConfigurationProperties(LeaderElectionProperties.class)
public class LeaderElectionStarter {

    @Autowired
    private LeaderElectionProperties properties;

    @Bean(destroyMethod = "close")
    public LeaderElection leaderElection() throws Exception {
        LeaderElection leaderElection = new LeaderElection(properties.getZkAddress(), properties.getInstance());
        leaderElection.connect();
        leaderElection.runForLeader();
        return leaderElection;
    }
}
